package com.xinchao.ck_mips.view;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.ContentObserver;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.xinchao.ck_mips.App;
import com.xinchao.ck_mips.BuildConfig;
import com.xinchao.ck_mips.R;
import com.xinchao.ck_mips.bean.ProgramBean;
import com.xinchao.ck_mips.bean.ProgramInfoBean;
import com.xinchao.ck_mips.bean.SourceInfoBean;
import com.xinchao.ck_mips.constant.CK;
import com.xinchao.ck_mips.event.DownloadCompleteEvent;
import com.xinchao.ck_mips.event.LightEvent;
import com.xinchao.ck_mips.logic.PlayLogic;
import com.xinchao.ck_mips.presenter.PlayPresenter;
import com.xinchao.ck_mips.utils.DeviceUtil;
import com.xinchao.ck_mips.utils.DialogUtils;
import com.xinchao.ck_mips.utils.FileUtils;
import com.xinchao.ck_mips.utils.ShareUtil;
import com.xinchao.ck_mips.utils.WatchDogUtil;
import com.xinchao.ck_mips.widgets.WheelPlayView;
import com.xinchao.devicemanage.util.DeviceTool;
import com.xinchao.rxtools.rxhttp.tools.IDisposable;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * Created by wq on 2019/5/6.
 * 播放界面
 */
public class PlayActivity extends BaseMvpActivity<IPlayView, PlayPresenter> implements IPlayView {
    private WheelPlayView mWheelPlayView;
    private String versionName;//当前播放节目版本号
    private SettingsContentObserver settingsContentObserver;

    private View view;
    /**
     * 所有节目组
     */
    private ArrayList<WheelPlayView.Source> allPlaySourceList = new ArrayList<>();

    /**
     * 所有素材列表集合（image;video;web）
     */
    private ArrayList<SourceInfoBean> allSourceInfoList = new ArrayList<>();
    /**
     * 当前素材开始播放时间
     */
    private long currentSourceStartTime;

    /**
     * 是否单个节目
     */
    private boolean isSingleProgram = false;
    private ImageView imgFlag;

    private boolean isFirst = true;
    private ProgramInfoBean currentProgramBean;//当前播放节目对象
    private ProgramInfoBean.FileInfoBean currentFileBean;//当前播放素材对象
    private List<ProgramInfoBean.FileInfoBean> infoList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (DeviceUtil.isLandscape(this)) {
            //横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        }

        setContentView(R.layout.activity_play);
        EventBus.getDefault().register(this);
        registerVolumeChangeReceiver();
        initView();
        imgFlag = findViewById(R.id.img_flag);

        view = findViewById(R.id.view);
        setBg(ShareUtil.getInstance().getInt(CK.CK_LIGHT, 100));
        if (Build.MODEL.contains("ZLP86Ni") || Build.MODEL.contains("IoT3288") || Build.MODEL.contains("3280") || Build.MODEL.contains("DS835")) {
            setWatchDog();
            PlayLogic.getInstance().setLocalOnOffTime(this);
        }
        //DeviceUtil.startScreen(this);
        FileUtils.saveTokenFile();
        PlayLogic.getInstance().delLocalFile();
        mPresenter.report(0, true);
        //上报离线监播数据,暂时屏蔽，循环调用接口，造成白屏卡死
        //mPresenter.reportOfflineData();
        mPresenter.getUpgradeReply("");
        setPlayProgram(true, true);
        mPresenter.reBootDevice();
        mPresenter.isConnectNetwork();
    }

    private void setWatchDog() {
        new WatchDogUtil(App.iBaseMachine, this);
    }

    private void setBg(int progress) {
        if (progress == 0) {
            view.setBackgroundColor(Color.parseColor("#000000"));
        } else {
            float ap = (100 - progress) / 100f;
            view.setAlpha(ap);
        }

    }

    /**
     * 设置节目（每播放完一轮，重新）
     *
     * @param isFirst
     */
    private void setPlayProgram(boolean isFirst, boolean isNeedDel) {
        PlayLogic.getInstance().downFile();
        List<ProgramBean> programBeanList = PlayLogic.getInstance().getProgram(isNeedDel);
        if (null != programBeanList && programBeanList.size() > 0) {
            setProgram(programBeanList, isFirst);
        } else {
            setDefaultSource(isFirst);
        }

    }

    /**
     * 设置节目素材播放逻辑
     *
     * @param isFirst true：数据库本地已有节目;false：服务器获取切换节目源
     */
    private void setProgram(List<ProgramBean> programList, boolean isFirst) {
        try {
            allPlaySourceList.clear();
            allSourceInfoList.clear();
            versionName = "";
            infoList.clear();
            isSingleProgram = false;

            if (programList != null && programList.size() > 0) {
                ArrayList<WheelPlayView.Source> mWheelList = new ArrayList<>();
                if (programList.size() > 1) {
                    isSingleProgram = false;
                } else {
                    isSingleProgram = true;
                }
                //多个节目
                for (int i = 0; i < programList.size(); i++) {
                    ProgramBean programBean = programList.get(i);
                    JSONArray sourceArray = new JSONArray(programBean.getFileInfo());
                    if (sourceArray != null && sourceArray.length() > 0) {
                        for (int n = 0; n < sourceArray.length(); n++) {
                            SourceInfoBean infoBean = new Gson().fromJson(sourceArray.getString(n), SourceInfoBean.class);
                            infoBean.setProgramVersion(programBean.getProgramVersion());
                            allSourceInfoList.add(infoBean);
                        }
                    }
                }

                for (int s = 0; s < allSourceInfoList.size(); s++) {
                    WheelPlayView.Source source = new WheelPlayView.Source();
                    SourceInfoBean sourceInfoBean = allSourceInfoList.get(s);
                    switch (sourceInfoBean.getFileType()) {
                        case "web":
                            //网页链接
                            source.setFilePath(sourceInfoBean.getUrl());
                            source.setType(WheelPlayView.FILE_TYPE_WEB);
                            break;
                        case "image":
                            //图片
                            source.setFilePath(FileUtils.getProgramFilePath(sourceInfoBean));
                            source.setType(WheelPlayView.FILE_TYPE_JPEG);
                            break;
                        case "video":
                            //视屏
                            source.setFilePath(FileUtils.getProgramFilePath(sourceInfoBean));
                            source.setType(WheelPlayView.FILE_TYPE_VIDEO);
                            break;
                    }
                    source.setFileUrl(sourceInfoBean.getUrl());
                    source.setFileName(sourceInfoBean.getFileName());
                    source.setPlay_time(sourceInfoBean.getDuration());
                    source.setIndex(s);
                    source.setVersion(sourceInfoBean.getProgramVersion());
                    mWheelList.add(source);
                }

                allPlaySourceList = mWheelList;
                if (isFirst) {
                    mWheelPlayView.setSources(mWheelList);
                    mWheelPlayView.start(this);
                } else {
                    mWheelPlayView.changeSources(mWheelList);
                }
                //设置当前播放的节目号
                versionName = allPlaySourceList.get(0).getVersion();
            } else {
                //本地资源全部过期，播放默认资源
                isSingleProgram = true;
                setDefaultSource(isFirst);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        mWheelPlayView = findViewById(R.id.wheelPlay);
        mWheelPlayView.setOnItemChangeListener(new WheelPlayView.onItemChangeListener() {
            @Override
            public void onItemChange(int position) {
                if (!TextUtils.isEmpty(versionName)) {
                    //排除默认资源,素材资源播放开始时间
                    try {
                        currentSourceStartTime = System.currentTimeMillis();
                        if (isSingleProgram) {
                            initReportFileObj(allPlaySourceList.get(position));
                            if (position == allPlaySourceList.size() - 1) {
                                //单轮播放完成
                                initReportProgramObj();
                                currentProgramBean.setFileList(infoList);
                                if (infoList.size() > 0) {
                                    currentProgramBean.setProgramPlayStartTime(infoList.get(0).getFilePlayStartTime());
                                    mPresenter.reportShow(currentProgramBean);
                                }
                                infoList.clear();
                                setPlayProgram(false, false);
                            }
                            versionName = allPlaySourceList.get(position).getVersion();
                        } else {
                            //多个节目
                            if (!allPlaySourceList.get(position).getVersion().equals(versionName)) {
                                //上报监播数据
                                initReportProgramObj();
                                currentProgramBean.setFileList(infoList);
                                if (infoList.size() > 0) {
                                    currentProgramBean.setProgramPlayStartTime(infoList.get(0).getFilePlayStartTime());
                                    mPresenter.reportShow(currentProgramBean);
                                }

                                infoList.clear();
                            }
                            initReportFileObj(allPlaySourceList.get(position));
                            versionName = allPlaySourceList.get(position).getVersion();

                            if (position == allPlaySourceList.size() - 1) {
                                //一轮播放完成后，重新判断
                                initReportProgramObj();
                                currentProgramBean.setFileList(infoList);
                                if (infoList.size() > 0) {
                                    currentProgramBean.setProgramPlayStartTime(infoList.get(0).getFilePlayStartTime());
                                    mPresenter.reportShow(currentProgramBean);
                                }
                                setPlayProgram(false, false);
                            }
                        }
                    } catch (IndexOutOfBoundsException e) {
                        e.printStackTrace();
                    }
                } else {
                    //默认素材播放完成
                    setPlayProgram(false, false);
                }
            }
        });
    }

    /**
     * 初始化监播上传对象
     */
    private void initReportFileObj(WheelPlayView.Source source) {
        currentFileBean = null;
        currentFileBean = new ProgramInfoBean.FileInfoBean();
        currentFileBean.setFilePlayStartTime(currentSourceStartTime);
        currentFileBean.setFileDuration(source.getPlay_time());
        currentFileBean.setFileName(source.getFileName());
        currentFileBean.setFileURL(source.getFileUrl());
        infoList.add(currentFileBean);
    }

    private void initReportProgramObj() {
        try {
            currentProgramBean = null;
            currentProgramBean = new ProgramInfoBean();
            currentProgramBean.setDeviceCode(DeviceTool.getDeviceCode());
            currentProgramBean.setProgramVersion(versionName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setDefaultSource(boolean isFirst) {
        versionName = "";
        isSingleProgram = true;
        // defaultSoureList.clear();
        ArrayList<WheelPlayView.Source> defaultList = new ArrayList<>();
        WheelPlayView.Source source = new WheelPlayView.Source();
        source.setType(WheelPlayView.FILE_TYPE_JPEG);
        source.setPlay_time(5000);
        source.setVersion("");
        source.setIndex(0);
        if (!FileUtils.isFileExist(CK.JPG_PATH[0]) || !FileUtils.isFileExist(CK.JPG_PATH[1])) {
            FileUtils.setDefaultJPGIntoCache(this, CK.DEFAULT_DIRS_PATH, CK.JPG_PATH);
        }

        if (DeviceUtil.isLandscape(this)) {
            //横屏素材
            source.setFileUrl(CK.JPG_PATH[0]);
            source.setFilePath(CK.JPG_PATH[0]);
        } else {
            //竖屏素材
            source.setFileUrl(CK.JPG_PATH[1]);
            source.setFilePath(CK.JPG_PATH[1]);
        }

        defaultList.add(source);

        if (isFirst) {
            mWheelPlayView.setSources(defaultList);
            mWheelPlayView.start(this);
        } else {
            mWheelPlayView.changeSources(defaultList);
        }

    }

    /**
     * 监听音量改变事件
     */
    private void registerVolumeChangeReceiver() {
        settingsContentObserver = new SettingsContentObserver(this, new Handler());
        getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, settingsContentObserver);
    }

    /**
     * 解绑音量改变事件
     */
    private void unregisterVolumeChangeReceiver() {
        getContentResolver().unregisterContentObserver(settingsContentObserver);
    }

    public class SettingsContentObserver extends ContentObserver {
        Context context;

        private SettingsContentObserver(Context c, Handler handler) {
            super(handler);
            context = c;
        }

        @Override
        public boolean deliverSelfNotifications() {
            return super.deliverSelfNotifications();
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            //本地设置同步服务器
            int vol = DeviceUtil.getVolume(PlayActivity.this);
            Log.v("xika", "音量:" + vol);
            App.iBaseMachine.setVolume(vol, AudioManager.STREAM_MUSIC);
            ShareUtil.getInstance().put(CK.SP_VOLUME, vol);
            mPresenter.settingSync(vol);
        }

    }


    @Override
    protected PlayPresenter createPrestener() {
        return new PlayPresenter();
    }

    @Override
    public IDisposable getDisposable() {
        return this;
    }

    @Subscribe
    public void onEventMainThread(Object event) {
        if (event instanceof DownloadCompleteEvent) {
            //播放新节目素材,保留老素材
            setPlayProgram(false, false);
        } else if (event instanceof LightEvent) {
            setBg(((LightEvent) event).progress);
        }

        /*else if (event instanceof NetWorkChangeEvent) {
            if (NetWorkUtil.isNetworkAvailable(PlayActivity.this)) {
                //上报离线监播数据
                mPresenter.reportOfflineData();
            }
        }*/
    }

    @Override
    public String getIP() {
        return DeviceUtil.getIP(this);
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void setScreenOnOff(String onTime, String offTime) {
        //设置开关屏
        DeviceUtil.getInstance().saveScreenOpenClose(onTime, offTime, this);
    }

    @Override
    public void finishAct() {
        //设备已解绑，清空token
        if (BuildConfig.DEBUG_LOG) {
            //测试环境
            ShareUtil.getInstance().remove(CK.SP_DEBUG_TOKEN);
            FileUtils.delDebugToken();
        } else {
            //正式环境
            ShareUtil.getInstance().remove(CK.SP_TOKEN);
            FileUtils.delToken();
        }

        startActivity(new Intent(PlayActivity.this, BindActivity.class));
        finish();
    }

    @Override
    public void setNetworkFlag(boolean isShow) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isShow) {
                    imgFlag.setVisibility(View.INVISIBLE);
                } else {
                    imgFlag.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWheelPlayView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirst) {
            mWheelPlayView.restart();
        }
        isFirst = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterVolumeChangeReceiver();
        //关闭看门狗
        if (Build.MODEL.contains("ZLP86Ni") || Build.MODEL.contains("IoT3288") || Build.MODEL.contains("3280") || Build.MODEL.contains("DS835")) {
            App.iBaseMachine.disable_watchdog();
        }

        removeAllDisposable();
        compositeDisposable = null;
        mPresenter.detachView();
    }

    @Override
    public void onBackPressed() {
        onDestroy();
        Process.killProcess(Process.myPid());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            DialogUtils.showInfoDialog(PlayActivity.this);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
